namespace BEGDC.CC.Web.UserControls.ECSCV
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Collections;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using BEGDC.CC.BL.CCFlow.CR;
	using BEGDC.CC.BL.CCFlow.ECSCV;
	using BEGDC.CC.Entity;
	using BEGDC.CC.BL.Workflow;
	using BEGDC.CC.BL.Common;
	using BEGDC.CC.BL.Common.Query;
	using BEGDC.Utility.Castle;

	/// <summary>
	///		Summary description for Summary.
	/// </summary>
	public class Feedback : BaseECSCV
	{
		#region Variables
		protected System.Web.UI.WebControls.ImageButton Btn_Save;
		protected System.Web.UI.WebControls.ImageButton btnQuery;
		protected System.Web.UI.WebControls.ImageButton btnReply;
		protected System.Web.UI.WebControls.TextBox Ctl_CompanyName;
		protected System.Web.UI.WebControls.TextBox Ctl_Date;
		protected System.Web.UI.HtmlControls.HtmlImage SurveyDateImg;
		protected System.Web.UI.WebControls.TextBox Ctl_VisitObj;
		protected System.Web.UI.WebControls.TextBox Ctl_TravelAgency;
		protected System.Web.UI.WebControls.TextBox Ctl_VI;
		protected System.Web.UI.WebControls.TextBox Ctl_Persons;
		protected System.Web.UI.WebControls.DataGrid DG_PartB;
		protected System.Web.UI.WebControls.DataGrid DG_PartA;
		protected System.Web.UI.WebControls.Label Label1;
		protected System.Web.UI.WebControls.ImageButton Btn_Submit;
		protected System.Web.UI.HtmlControls.HtmlTableRow tr_Title;
		protected System.Web.UI.WebControls.TextBox tbScoreARowCount;
		protected System.Web.UI.WebControls.TextBox tbScoreBRowCount;
		protected System.Web.UI.WebControls.TextBox tbScoreA;
		protected System.Web.UI.WebControls.TextBox tbScoreB;
		protected System.Web.UI.WebControls.TextBox tbSuggestionA;
		protected System.Web.UI.WebControls.TextBox tbSuggestionB;
		protected System.Web.UI.WebControls.TextBox tbComment;
		protected System.Web.UI.WebControls.DropDownList ddlTravelAgency;
		protected System.Web.UI.WebControls.Label lbAppNo;
		protected System.Web.UI.WebControls.TextBox tbOperationFlag;
		protected System.Web.UI.WebControls.TextBox tbOperationContent;
		protected System.Web.UI.WebControls.DataGrid dgCostCenter;
		protected bool IsFeedbackStep = true;
		#endregion

		protected string Step
		{
			get
			{
				IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
				FlowInstance flowInstance = queryService.QueryFlowInstance( this.AppID );
				if( flowInstance == null )
					return "Close";
				else
					return flowInstance.CurrentActiveStep.StepCode;
			}
		}
		protected bool BeginFeedback
		{
			get
			{
				IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
				return queryService.BeginFeedback( this.AppID );
			}
		}
		private bool IsView
		{
			get
			{
				string state = this.Request.QueryString["State"];
				if(state == null) return false;
				if(state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.End
					|| state == SysDicItem.ProjectStatusFlag.Pending || state == SysDicItem.ProjectStatusFlag.Participation)
					return true;
				else
					return false;
			}
		}
		private int PaymentID
		{
			set
			{
				ViewState["paymentID"] = value;
			}
			get
			{
				if(ViewState["paymentID"] == null)
					return 0;
				return Convert.ToInt32(ViewState["paymentID"]);
			}
		}

		private void Page_Load(object sender, System.EventArgs e)
		{
			if(!this.IsPostBack)
			{
				base.PreInitForm();
				//				SetStamp();

				this.Btn_Save.Attributes["onclick"] = "javascript:OnSave();";
				this.Btn_Submit.Attributes["onclick"] = "javascript:OnSubmit();";
				this.btnReply.Attributes.Add("onclick", "javascript:OpenReplyPane();");
				this.btnQuery.Attributes.Add("onclick", "javascript:OpenQueryPane("+Request.QueryString["AppID"]+");");

				InitForm();
			}
			ButtonStatusSetting();
		}

		private void BindReadOnlyStatus()
		{
			this.Label1.Text = string.Empty;
			this.Btn_Save.Visible = false;
			this.Btn_Submit.Visible = false;
			this.Ctl_VisitObj.Enabled = false;
			this.Ctl_TravelAgency.Enabled = false;
			this.Ctl_VI.Enabled = false;
			this.Ctl_Persons.Enabled = false;
			//			this.Ctl_Score.Enabled = false;

			foreach(DataGridItem row in this.DG_PartA.Items)
			{
				DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreA");
				TextBox Tx_Comment = (TextBox)row.FindControl("Ctl_CommentA");

				Dp_Score.Enabled = false;
				Tx_Comment.Enabled = false;
			}

			foreach(DataGridItem row in this.DG_PartB.Items)
			{
				DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreB");
				TextBox Tx_Comment = (TextBox)row.FindControl("Ctl_CommentB");

				Dp_Score.Enabled = false;
				Tx_Comment.Enabled = false;
			}

			if(this.IsView)
				tr_Title.Visible = false;
			this.ddlTravelAgency.Enabled = false;
		}

		#region InitForm
		private void InitForm()
		{
			bool isReadOnly = true;
			long flowId  = this.LoadApplication();

			WebUtility.BuildDropDown(this.ddlTravelAgency,BEGDC.CC.BL.Common.DicType.TravelAgency,false,false);
			this.ddlTravelAgency.Items.Insert(0,new System.Web.UI.WebControls.ListItem("Others, Please input the name","-1"));
			ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
			this.lbAppNo.Text = "("+this.Application.AppNo+")";

			//BIND PART_A QUESTIONS
			DataTable PartA = CRService.GetSurveyQuestions(BEGDC.CC.BL.Workflow.WorkflowTypes.CV.ToString(), "PartA-Visit",true);
			if(PartA!=null&&PartA.Rows.Count>0)
			{
				this.DG_PartA.DataSource = PartA;
				this.DG_PartA.DataBind();
				this.tbScoreARowCount.Text = PartA.Rows.Count.ToString();
			}

			//BIND PART_B QUESTIONS
			DataTable PartB = CRService.GetSurveyQuestions(BEGDC.CC.BL.Workflow.WorkflowTypes.CV.ToString(),"PartB-Reception",true);
			if(PartB!=null&&PartB.Rows.Count>0)
			{
				this.DG_PartB.DataSource = PartB;
				this.DG_PartB.DataBind();
				this.tbScoreBRowCount.Text = PartB.Rows.Count.ToString();
			}

			if(this.Application!=null)
			{
				//Customer Survey
				BEGDC.CC.Entity.CustomerSurvey survey = CRService.GetCustomerSurvey(this.Application.Id);

				if(survey!=null)
				{
					bool isOtherTravel = true;
					this.Ctl_VisitObj.Text = survey.VisitObjective;
					for(int i=0; i<this.ddlTravelAgency.Items.Count; i++)
					{
						if(survey.TravelAgency == this.ddlTravelAgency.Items[i].Text)
						{
							this.ddlTravelAgency.Items[i].Selected = true;
							isOtherTravel = false;
							break;
						}
					}
					if(isOtherTravel)
						this.Ctl_TravelAgency.Text = survey.TravelAgency;
					this.Ctl_VI.Text = survey.Itinerary;
					this.Ctl_Persons.Text = survey.NumberOfPerson;
					this.tbScoreA.Text = survey.ScoreA.ToString();
					this.tbScoreB.Text = survey.ScoreB.ToString();
					this.tbSuggestionA.Text = survey.CommentA;
					this.tbSuggestionB.Text = survey.CommentB;
				}

				if(survey!=null)
				{
					DataTable AnswerTable = CRService.GetSurveyAnswer(survey.Id);
					if(AnswerTable!=null&&AnswerTable.Rows.Count>0)
					{
						DoBindAnswersA(this.DG_PartA, AnswerTable);
						DoBindAnswersB(this.DG_PartB, AnswerTable);
					}
				}
			}

			IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
			PaymentInfo payment = queryService.GetPaymentInfo(this.AppID);
			this.PaymentID = payment.Id;

			BindCostCenter();
		}
		#endregion

		#region Do Bind Answers
		private void DoBindAnswersA(DataGrid datagrid, DataTable AnswerTable)
		{
			DataRow AnsRow = null;
			foreach(DataGridItem row in datagrid.Items)
			{
				string QuestionID = row.Cells[0].Text.ToString();
				AnsRow = SearchDataTable(AnswerTable,QuestionID);
				if(AnsRow!=null)
				{
					DropDownList Score = (DropDownList)row.FindControl("Ctrl_ScoreA");
					TextBox Comment = (TextBox)row.FindControl("Ctl_CommentA");
					if(AnsRow["Score"]!=null||AnsRow["Score"].ToString()!="")
					{
						Score.SelectedIndex = Score.Items.IndexOf(Score.Items.FindByValue(AnsRow["Score"].ToString()));
					}
					Comment.Text = AnsRow["Comment"].ToString();
				}
			}
		}
		private void DoBindAnswersB(DataGrid datagrid, DataTable AnswerTable)
		{
			DataRow AnsRow = null;
			foreach(DataGridItem row in datagrid.Items)
			{
				string QuestionID = row.Cells[0].Text.ToString();
				AnsRow = SearchDataTable(AnswerTable,QuestionID);
				if(AnsRow!=null)
				{
					DropDownList Score = (DropDownList)row.FindControl("Ctrl_ScoreB");
					TextBox Comment = (TextBox)row.FindControl("Ctl_CommentB");
					if(AnsRow["Score"]!=null||AnsRow["Score"].ToString()!="")
					{
						Score.SelectedIndex = Score.Items.IndexOf(Score.Items.FindByValue(AnsRow["Score"].ToString()));
					}
					Comment.Text = AnsRow["Comment"].ToString();
					
				}
			}
		}

		private DataRow SearchDataTable(DataTable table, string Id)
		{
			if(table!=null)
			{
				for(int i=0;i<table.Rows.Count;i++)
				{
					if((table.Rows[i]["QuestionId"].ToString())==Id)
					{
						return table.Rows[i];
					}
				}
			}
			return null;
		}
		#endregion

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnQuery.Click += new System.Web.UI.ImageClickEventHandler(this.btnQuery_Click);
			this.btnReply.Click += new System.Web.UI.ImageClickEventHandler(this.btnReply_Click);
			this.Btn_Save.Click += new System.Web.UI.ImageClickEventHandler(this.Btn_Save_Click);
			this.Btn_Submit.Click += new System.Web.UI.ImageClickEventHandler(this.Btn_Submit_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		#region BUILD SURVEY DATA
		public BEGDC.CC.Entity.CustomerSurvey BuildCustomerSurvey()
		{
			if(this.AppID==0||this.Application==null) return null;

			ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
			BEGDC.CC.Entity.CustomerSurvey survey = CRService.GetCustomerSurvey(this.AppID);

			if(survey == null)
			{
				survey = new BEGDC.CC.Entity.CustomerSurvey();
				survey.Id = 0;
				survey.Application = this.Application;
			}

			survey.VisitObjective = this.Ctl_VisitObj.Text;
			if(this.ddlTravelAgency.SelectedValue == "-1")
				survey.TravelAgency = this.Ctl_TravelAgency.Text;
			else
				survey.TravelAgency = this.ddlTravelAgency.SelectedItem.Text;
			survey.Itinerary = this.Ctl_VI.Text;
			survey.NumberOfPerson = this.Ctl_Persons.Text;
			survey.ScoreA = Convert.ToDecimal(this.tbScoreA.Text);
			survey.ScoreB = Convert.ToDecimal(this.tbScoreB.Text);
			survey.CommentA = this.tbSuggestionA.Text;
			survey.CommentB = this.tbSuggestionB.Text;
 
			return survey;
		}

		private IList DoAnswerList(int SurveyId)
		{
			ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
			IList QuestionList = CRService.GetSurveyQuestionList();
			IList AnswerList = CRService.GetSurveyAnswerList(SurveyId);
			if(AnswerList==null)
			{
				AnswerList = new ArrayList();
			}

			if(this.DG_PartA.Items.Count>0)
			{
				foreach(DataGridItem row in this.DG_PartA.Items)
				{
					int QuestionId = Convert.ToInt32(row.Cells[0].Text.ToString());
					DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreA");
					TextBox Tx_Comment = (TextBox)row.FindControl("Ctl_CommentA");

					BEGDC.CC.Entity.SurveyAnswer sa =  SearchArrayList(AnswerList,QuestionId);

					if(sa==null)
					{
						sa = new BEGDC.CC.Entity.SurveyAnswer();
						sa.SurveyQuestion = SearchQuestionList(QuestionList,QuestionId);
						sa.Score = Dp_Score.SelectedValue.ToString();
						sa.Comment = Tx_Comment.Text;
						AnswerList.Add(sa);
					}
					else
					{
						sa.Score = Dp_Score.SelectedValue.ToString();
						sa.Comment = Tx_Comment.Text;
					}
				}
			}

			if(this.DG_PartB.Items.Count>0)
			{
				foreach(DataGridItem row in this.DG_PartB.Items)
				{
					int QuestionId = Convert.ToInt32(row.Cells[0].Text.ToString());
					DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreB");
					TextBox Tx_Comment = (TextBox)row.FindControl("Ctl_CommentB");

					BEGDC.CC.Entity.SurveyAnswer sa =  SearchArrayList(AnswerList,QuestionId);

					if(sa==null)
					{
						sa = new BEGDC.CC.Entity.SurveyAnswer();
						sa.SurveyQuestion = SearchQuestionList(QuestionList,QuestionId);
						sa.Score = Dp_Score.SelectedValue.ToString();
						sa.Comment = Tx_Comment.Text;
						AnswerList.Add(sa);
					}
					else
					{
						sa.Score = Dp_Score.SelectedValue.ToString();
						sa.Comment = Tx_Comment.Text;
					}
				}
			}
			return AnswerList;
		}

		private BEGDC.CC.Entity.SurveyAnswer SearchArrayList(IList AnswerList, int QuestionId)
		{
			if(AnswerList!=null)
			{
				for(int i=0;i<AnswerList.Count;i++)
				{
					BEGDC.CC.Entity.SurveyAnswer sa = AnswerList[i] as BEGDC.CC.Entity.SurveyAnswer;
					if(sa.SurveyQuestion.Id==QuestionId)
					{
						return sa;
					}
				}
			}
			return null;
		}

		private BEGDC.CC.Entity.SurveyQuestion SearchQuestionList(IList QuestionList, int QuestionId)
		{
			if(QuestionList!=null)
			{
				for(int i=0;i<QuestionList.Count;i++)
				{
					BEGDC.CC.Entity.SurveyQuestion sq = QuestionList[i] as BEGDC.CC.Entity.SurveyQuestion;
					if(sq.Id==QuestionId)
					{
						return sq;
					}
				}
			}
			return null;
		}
		#endregion

		#region Save
		private void Btn_Save_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
				BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);

				BEGDC.CC.Entity.CustomerSurvey survey = BuildCustomerSurvey();
				IList AnswerList = DoAnswerList(survey.Id);

				CRService.SaveSurvey(App,survey,AnswerList);
				Page.RegisterClientScriptBlock("","<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');</script>");
			}
			catch
			{
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
			}
		}
		#endregion

		#region Submit
		private void Btn_Submit_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				ICR crService = AppContainer.Instance[ServiceConst.CRService] as ICR;
				BEGDC.CC.Entity.Application App = crService.GetApplication(this.AppID);
				
				BEGDC.CC.Entity.CustomerSurvey survey = BuildCustomerSurvey();
				IList AnswerList = DoAnswerList(survey.Id);

				IECSCV ocvService = AppContainer.Instance[ServiceConst.ECSCVService] as IECSCV;
				ocvService.SubmitSurvey(App,survey,AnswerList);
				Page.RegisterClientScriptBlock("","<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');</script><script>window.close();</script>");
			}
			catch
			{
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
			}
		}
		#endregion

		private void Btn_Export_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				ExcelTool.ICCExcelExport excelExport=new ExcelTool.ExportCVForm();
				excelExport.Export(this.Page, this.AppID );

				Page.RegisterClientScriptBlock("","<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');</script>");
			}
			catch (BEGDC.Utility.ExceptionManagement.GDCException exp)
			{
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.ErrorMessage.Export_0001 + "');</script>");
			}
		}

		protected override void ButtonStatusSetting()
		{			
			if( this.Access == null )
				return;

			this.Btn_Save.Visible = this.Access.IsButtonVisible(CVTransitionList.Save);
			this.Btn_Submit.Visible = this.Access.IsButtonVisible(CVTransitionList.Submit);
			this.btnQuery.Visible = this.Access.IsButtonVisible(CVTransitionList.Query);
			this.btnReply.Visible = this.Access.IsButtonVisible(CVTransitionList.Reply);

			if(Access.IsReadOnly && this.Step != BEGDC.CC.BL.Workflow.WorkTransition.CV_Feedback )
			{
				IsFeedbackStep = false;
				BindReadOnlyStatus();
			}

			if( this.Access.IsHideAllButton)
				tr_Title.Visible = false;
		}

		private void btnReply_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				// Save Feedback
				ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
				BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);

				BEGDC.CC.Entity.CustomerSurvey survey = BuildCustomerSurvey();
				IList AnswerList = DoAnswerList(survey.Id);

				CRService.SaveSurvey(App,survey,AnswerList);

				IECSCV ocvService = AppContainer.Instance[ServiceConst.ECSCVService] as IECSCV;
				ocvService.ReplyQuery(Convert.ToInt64(Request.QueryString["FlowID"]), WebUtility.DeCodeString(Server, tbComment.Text));
				
				Page.RegisterClientScriptBlock("","<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');</script><script>window.close();</script>");
			}
			catch
			{
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
			}
		}

		private void btnQuery_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				if(this.tbOperationFlag.Text == "query")
				{
					IECSCV ocvService = AppContainer.Instance[ServiceConst.ECSCVService] as IECSCV;
					ocvService.Query(Convert.ToInt64(Request.QueryString["FlowID"]), this.tbOperationContent.Text, Session["Comment"].ToString());
				}
				Page.RegisterClientScriptBlock("","<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");
			}
			catch
			{
				Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV002 + "');</script>");
			}
		}

		private void BindCostCenter()
		{
			DataTable CostCenter = null;
			if(Session[SessionFlag.CostCenter] != null)
			{
				CostCenter = (DataTable)Session[SessionFlag.CostCenter];
			}
			else
			{
				if(this.PaymentID > 0)
				{
					IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
					CostCenter = queryService.GetCostCenter(this.PaymentID);
				}
				if(CostCenter == null || CostCenter.Rows.Count == 0)
				{
					CostCenter = new DataTable();
					CostCenter.Columns.Add(new DataColumn("Id", typeof(System.String)));
					CostCenter.Columns.Add(new DataColumn("CostCenterCode", typeof(System.String)));
					CostCenter.Columns.Add(new DataColumn("Cost", typeof(System.String)));
					CostCenter.Columns.Add(new DataColumn("ActualCost", typeof(System.String)));
				}
				Session[SessionFlag.CostCenter] = CostCenter;
			}
			this.dgCostCenter.DataSource = this.SetRowID(CostCenter);
			this.dgCostCenter.DataBind();

//			this.lbCostSum.Text = this.CalculateCostSum();

			if(!(this.Step == WorkTransition.CV_Close || this.Step == WorkTransition.End))
				dgCostCenter.Columns[3].Visible = false;
		}

		private DataTable SetRowID(DataTable table)
		{
			if(table != null && table.Rows.Count >0)
				for(int i=1; i<=table.Rows.Count; i++)
				{
					table.Rows[i-1][0] = i.ToString();
				}
			return table;
		}

	}
}
